import os
import sys
import logging

from pyhudson.command_line.base import base
from pyhudson.hudson import hudson

log = logging.getLogger(__name__)

class hudson_invoke( base ):
    
    @classmethod
    def mkparser(cls):
        parser = base.mkparser( )
        
        DEFAULT_HUDSON_BASE_URL=os.environ.get( "HUDSON_URL", "http://localhost/hudson" )
        
        parser.help_text = "Execute a number of hudson jobs on the server of your choice. Optionally block until the jobs are complete."
        
        parser.add_option("-H", "--hudsonbase", dest="hudsonbase",
                          help="Base URL for the Hudson server, default is %s" % DEFAULT_HUDSON_BASE_URL ,
                          type="str",
                          default=DEFAULT_HUDSON_BASE_URL, )
        
        parser.add_option("-b", "--block", dest="block",
                          help="Block until each of the jobs is complete." ,
                          action="store_true",
                          default=False )
        
        parser.add_option("-t", "--token", dest="token",
                          help="Optional security token." ,
                          default=None )
        
        return parser
        
    @classmethod
    def main(cls):
        parser = cls.mkparser()
        options, args = parser.parse_args()
        try:
            assert len( args ) > 0, "Need to specify at least one job name"
        except AssertionError, e:
            log.critical( e[0] )
            parser.print_help()
            sys.exit(1)
            
        invoker = cls( options, args )
        invoker()
        
    def __init__( self, options, jobs ):
        self.options = options
        self.jobs = jobs
        
    def __call__(self):
        for job in self.jobs:
            self.invokejob( job, block=self.options.block, hudsonbase=self.options.hudsonbase, token=self.options.token )
            
    def invokejob(self, jobname, block, hudsonbase, token ):
        assert type(block) == bool
        assert type(hudsonbase) == str
        assert type(jobname) == str
        assert token == None or isinstance( token, str )
        
        hudsonserver = hudson( hudsonbase )
        job = hudsonserver[ jobname ]
        job.invoke( securitytoken=token, block=block )

    
def main(  ):
    logging.basicConfig()
    logging.getLogger("").setLevel( logging.INFO )
    hudson_invoke.main()